<?php
/**
 * ============================================================================
 * Copyright (c) 2015-2018 贵州大师兄信息技术有限公司 All rights reserved.
 * siteַ: http://www.dsxcms.com
 * ============================================================================
 * @author:     David Song<songdewei@163.com>
 * @version:    v1.0.0
 * ---------------------------------------------
 * Date: 2018-11-27
 * Time: 15:36
 */

namespace App\Library\Mall\Shop;


use Illuminate\Http\Request;

trait AttributeManagers
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAttributes(Request $request)
    {
        $items = $this->shop->shopAttributes()->with('values')->get(['attr_id', 'attr_name']);
        return ajaxReturn(['items'=>$items]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function saveAttribute(Request $request)
    {
        $attr_name = $request->input('attr_name');
        if ($attr_name)
        {
            $attribute = $this->shop->shopAttributes()
                ->where('attr_name', $attr_name)
                ->firstOrCreate(['attr_name'=>$attr_name]);
            return ajaxReturn(compact('attribute'));
        }
        return ajaxError(201, 'invalid parameter');
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getValues(Request $request)
    {
        $attr_id = $request->input('attr_id', 0);
        $items = $this->shop->shopAttributes()->find($attr_id)->values;
        return ajaxReturn(compact('items'));
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function saveValue(Request $request)
    {
        $attr_id  = $request->input('attr_id', 0);
        $newvalue = $request->input('value');
        if ($attr_id && $newvalue)
        {
            $value = $this->shop->shopAttributes()->find($attr_id)
                ->values()
                ->where('value', $newvalue)
                ->firstOrCreate(['value'=>$newvalue]);
            return ajaxReturn(['value'=>$value]);
        }

        return ajaxError(201, 'invalid parameter');
    }
}
